import 'dart:collection';
import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:dart_date/dart_date.dart';
import 'package:flutter/cupertino.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../../pages/utils/bt_constants.dart';

Future<Response<dynamic>> googleTranslate(dynamic urlParams) async {
  var dio = Dio();
  var url = 'https://translation.googleapis.com/language/translate/v2';

  var response = await dio.post(url, queryParameters: urlParams);
  return response;
}

class BtGoogleTranslationStore {
  LinkedHashMap translatedDataMap = LinkedHashMap();

  var saveTime = 0;

  var readySaveCount = 0;

  late SharedPreferences _prefs;

  String _googleTranslationKey = '';

  BtGoogleTranslationStore._internal();

  factory BtGoogleTranslationStore() => _instance;

  static final BtGoogleTranslationStore _instance = BtGoogleTranslationStore._internal();

  void init() {
    SharedPreferences.getInstance().then((value) {
      _prefs = value;
      _googleTranslationKey = _prefs.getString(googleTranslationKey) ?? '';
      translatedDataMap = jsonDecode(_prefs.getString(translateCacheData) ?? "{}");
    });
  }

  Future<String> getTranslatedTextByGoogleTranslate(String content) async {
    var urlParams = {
      "key": _googleTranslationKey,
      "target": const Locale.fromSubtags().languageCode, // 目标语言Code，从设备中获取当前语言。
      "q": content, // 被翻译的文案
      "format": 'text'
    };
    var res = await compute(googleTranslate, urlParams);
    String translatedText = res.data["data"]["translations"][0]["translatedText"];
    translatedDataMap[_toMd5String(content)] = translatedText;
    _saveTranslatedData();

    return translatedText;
  }

  hasTranslated(String content) {
    return translatedDataMap.containsKey(_toMd5String(content));
  }

  String getTranslatedTextFromCache(String content) {
    if (hasTranslated(content)) {
      return translatedDataMap[_toMd5String(content)];
    }

    return '';
  }

  Future<String> getTranslatedText(String content) async {
    var translateText = translatedDataMap[_toMd5String(content)];
    if (translateText != null) {
      return translateText;
    }

    translateText = await getTranslatedTextByGoogleTranslate(content);
    return translateText;
  }

  _saveTranslatedData() {
    readySaveCount++;
    if (readySaveCount > 10) {
      if (translatedDataMap.length > 9999) {
        translatedDataMap.remove(translatedDataMap.keys.toList()[0]);
      }
      var currentTime = DateTime.now().secondsSinceEpoch;
      if (currentTime - saveTime > 20) {
        _prefs.setString(translateCacheData, jsonEncode(translatedDataMap));
        readySaveCount = 0;
        saveTime = currentTime;
      }
    }
  }

  _toMd5String(String content) {
    return md5.convert(utf8.encode(content)).toString();
  }
}
